package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.ex.CustomerException;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 套餐业务层实现
 */
@Service
@Transactional
@Slf4j
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private SetmealService setmealMapper;

    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private CategoryService categoryService;

    /**
     * 新增套餐
     *
     * @param setmealDto
     * @return
     */
    @Override
    public R addWithDishes(SetmealDto setmealDto) {
        // 保存套餐数据
        setmealDto.setIsDeleted(0);
        this.save(setmealDto);
        // 保存套餐跟菜品关联数据
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes().stream().map(item -> {
            item.setSetmealId(setmealDto.getId()); // 套餐id
            item.setSort(0);    // 排序
            item.setIsDeleted(0);   // 是否删除
            return item;
        }).collect(Collectors.toList());

        setmealDishService.saveBatch(setmealDishes);
        return R.success("套餐保存成功!!");
    }

    /**
     * 分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @Override
    public R findPage(Integer page, Integer pageSize, String name) {
        // 分页查询
        Page<Setmeal> setmealPage = new Page<>(page, pageSize);

        LambdaQueryWrapper<Setmeal> lqw = Wrappers.<Setmeal>lambdaQuery()
                .like(StringUtils.isNotBlank(name), Setmeal::getName, name)
                .orderByDesc(Setmeal::getUpdateTime);

        this.page(setmealPage, lqw);

        // 处理分页数据，返回给前端
        Page<SetmealDto> setmealDtoPage = new Page<>(page, pageSize);
        BeanUtils.copyProperties(setmealPage, setmealDtoPage, "records");

        List<SetmealDto> setmealDtos = setmealPage.getRecords().stream()
                .map(item -> {
                    SetmealDto setmealDto = new SetmealDto();
                    BeanUtils.copyProperties(item, setmealDto);
                    Category category = categoryService.getById(setmealDto.getCategoryId());
                    setmealDto.setCategoryName(category.getName());
                    return setmealDto;
                })
                .collect(Collectors.toList());
        setmealDtoPage.setRecords(setmealDtos);

        return R.success(setmealDtoPage);
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @Override
    public R deleteByids(List<Long> ids) {
        // 判断当前套餐是否可以删除
        int count = this.count(Wrappers.<Setmeal>lambdaQuery()
                .in(Setmeal::getId, ids)
                .eq(Setmeal::getStatus, 1));
        if (count > 0) {
            // 其中有套餐实在售卖状态，不能删除
            throw new CustomerException("有套餐正在售卖，不能删除");
        }

        // 删除套餐基本数据  setmeal
        this.removeByIds(ids);

        //删除套餐菜品关联数据 setmeal_dish
        LambdaQueryWrapper<SetmealDish> wrapper = Wrappers.<SetmealDish>lambdaQuery().in(SetmealDish::getSetmealId, ids);
        setmealDishService.remove(wrapper);

        return R.success("套餐删除成功");
    }

    /**
     * 批量修改状态
     *
     * @param status
     * @param ids
     * @return
     */
    @Override
    public R modifySetmealStatus(Integer status, List<Long> ids) {
        List<Setmeal> setmeals = new ArrayList<>();
        for (Long id : ids) {
            Setmeal setmeal = new Setmeal();
            setmeal.setId(id);
            setmeal.setStatus(status);
            setmeals.add(setmeal);
        }

        this.updateBatchById(setmeals);
        return R.success("套餐状态修改成功");
    }

    /**
     * 根据分类ID和状态查询
     *
     * @param setmeal
     * @return
     */
    @Override
    public R findAllSetmeal(Setmeal setmeal) {
        LambdaQueryWrapper<Setmeal> lqw = Wrappers.<Setmeal>lambdaQuery().eq(setmeal.getCategoryId() != null, Setmeal::getCategoryId, setmeal.getCategoryId())
                .eq(setmeal.getStatus() != null, Setmeal::getStatus, setmeal.getStatus())
                .orderByDesc(Setmeal::getUpdateTime);
        return R.success(this.list(lqw));
    }

    /**
     * 查询回显
     *
     * @param setmealId
     * @return
     */
    @Override
    public R findById(Long setmealId) {
        Setmeal setmeal = this.getOne(Wrappers.<Setmeal>lambdaQuery().eq(setmealId != null, Setmeal::getId, setmealId));
        if (setmeal == null) {
            throw new CustomerException("套餐详情异常");
        }
        SetmealDto setmealDto = new SetmealDto();
        BeanUtils.copyProperties(setmeal, setmealDto);
        List<SetmealDish> setmealDishes = setmealDishService.list(Wrappers.<SetmealDish>lambdaQuery().eq(SetmealDish::getSetmealId, setmealId));
        setmealDto.setSetmealDishes(setmealDishes);

        return R.success(setmealDto);
    }

    /**
     * 修改套餐
     *
     * @param setmealDto
     * @return
     */
    @Override
    public R modifySetmeal(SetmealDto setmealDto) {
        if (setmealDto == null) {
            throw new CustomerException("无套餐数据");
        }

        // 获取套餐id
        Long setmealId = setmealDto.getId();

        // 获取菜品
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes().stream().map(item-> {
            item.setSetmealId(setmealId);
            return item;
        }).collect(Collectors.toList());

        // 删除原有套餐数据
        setmealDishService.remove( Wrappers.<SetmealDish>lambdaQuery().eq(SetmealDish::getSetmealId,setmealId));
        // 保存套餐菜品数据
        setmealDishService.saveBatch(setmealDishes);

        // 保存套餐数据
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDto,setmeal);

        this.updateById(setmeal);

        return R.success("套餐修改成功");
    }


}